package com.atguigu.service_edu.controller.front;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.service_edu.client.UcenterClient;
import com.atguigu.service_edu.entity.EduComment;
import com.atguigu.service_edu.service.EduCommentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author clark
 * @since 2020-11-18
 */
@CrossOrigin
@RestController
@RequestMapping("/eduservice/comment")
public class EduCommentFrontController {

    @Autowired
    private EduCommentService eduCommentService;
    @Autowired
    private UcenterClient ucenterClient;


    @ApiOperation(value = "评论列表")
    @PostMapping("pageList/{courseId}/{page}/{limit}")
    public R pageList(@PathVariable String courseId, @PathVariable Long page ,@PathVariable Long limit){
        Page<EduComment> pageParam = new Page<>(page, limit);
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        wrapper.orderByAsc("gmt_create");
        eduCommentService.page(pageParam,wrapper);
        Map map = new HashMap();
        map.put("items", pageParam.getRecords());
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return R.ok().data(map);
    }

    @ApiOperation(value = "新增评论")
    @PostMapping("save")
    public R save(@RequestBody EduComment eduComment, HttpServletRequest request){
        String id = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(id)) {
            return R.error().code(28004).message("请登录");
        }
        Map map = ucenterClient.getMemberInfoById(id);
        eduComment.setMemberId((String) map.get("memberId"));
        eduComment.setAvatar((String) map.get("avatar"));
        eduComment.setNickname((String) map.get("nickName"));
        eduCommentService.save(eduComment);

        return R.ok();
    }



}

